﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Web.Interfaces;

namespace Cofe.Web.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class StreamResponseFormatter : IHttpResponseMessageFormatter
    {
        public bool CanCreateResponse(HttpRequestMessage request,
            object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            return (returnVal is StreamContainer);
        }

        public HttpResponseMessage CreateResponse(HttpRequestMessage request,
            object returnVal, ParameterDic pd, ResponseFormatterInfo info)
        {
            StreamContainer sc = returnVal as StreamContainer;
            if (sc == null)
                throw new Exception();

            HttpResponseMessage result = new HttpResponseMessage(info.StatusCode);
            result.Content = new StreamContent(sc.Stream);
            if (!(string.IsNullOrEmpty(sc.Path)))
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = PathFE.GetFileName(sc.Path)
                };

            return result;
        }
    }
}
